/**
 * 
 */
package forumTransform.forumTransformID;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import org.apache.http.client.ClientProtocolException;

/**
 * @author Dan
 * {
 "kind": "blogger#blog",
 "id": "29059245",
 "name": "FemaleScienceProfessor",
 "description": "Musings of a science professor at a large research university.",
 "published": "2006-10-05T23:18:02-05:00",
 "updated": "2013-07-24T09:03:19-05:00",
 "url": "http://science-professor.blogspot.com/",
 "selfLink": "https://www.googleapis.com/blogger/v3/blogs/29059245",
 "posts": {
  "totalItems": 1487,
  "selfLink": "https://www.googleapis.com/blogger/v3/blogs/29059245/posts"
 },
 "pages": {
  "totalItems": 0,
  "selfLink": "https://www.googleapis.com/blogger/v3/blogs/29059245/pages"
 },
 "locale": {
  "language": "en",
  "country": "US",
  "variant": ""
 }
}
 *
 */
public class BlogspotJSON extends Blog {
	 private String id;
	 private String name;
	 private String url;
	 private BPosts posts;
	 private String nextPageToken;
	 private String prevPageToken;
	 
	 private Integer found;
	 private List<BPost> items;
	 private List<BComment> comments;
	 TreeSet<String>	users = new TreeSet<String>();
	 
	 TreeSet<String> usersURL = new TreeSet<String>();
	 
	 private List<Utterance> utterances = new ArrayList<Utterance>();
	 private HashMap<String,ParticipationLog> plList = new HashMap<String, ParticipationLog>();
	 
	 public Integer getFound() {
		return found;
	}
	public void setFound(Integer found) {
		this.found = found;
	}
	public List<BPost> getItems() {
		return items;
	}
	public void setItems(List<BPost> items) {
		this.items = items;
	}
	
	public BlogspotJSON() {
		super();
	}
	
	public void populateBlog() throws ClientProtocolException, IOException{
		this.addPosts(Utils.getBPosts(this.getId()));
	}
	

	public void populateComments() throws ClientProtocolException, IOException{
		this.addComments(Utils.getBComments(this.getId(), this.getItems()));
	}
	
	
//	public void populateComments2(){
//
//			BlogspotJSON blog = Utils.createBBlog(getBlogId(),true);
//			int pages 	 = blog.getFound()/100;
//			int overflow = blog.getFound()%100;
//			if (overflow >0)
//				pages ++;
//			for (int i = 0; i < pages; i++) {
//				try {
//					//blog = Utils.getInfoComments2(getBlogId(), 100, i*100);
//					this.addComments(Utils.getBInfoComments2(getBlogId(), 100, i*100));
//				} catch (ClientProtocolException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				
//			}
//			
//	}


	public void addPosts(List<BPost> items){
		if(items !=null){
			if(this.items == null){
				this.items = new ArrayList<BPost>();
			}
			this.items.addAll(items);
		}
	}
	
	public void addComments(List<BComment> items){
		if(items !=null){
			if(this.comments == null)
				this.comments = new ArrayList<BComment>();
			this.comments.addAll(items);	
		}
	}
	
	public List<BComment> getComments() {
		return comments;
	}
	public void setComments(List<BComment> comments) {
		this.comments = comments;
	}
	
	public void process(){
		
//		TreeSet<String> users = new TreeSet<String>();
		users.addAll(getAllUsers());
	}

	private Collection<String> getAllUsers() {
		TreeSet<String>	result = new TreeSet<String>();
		HashMap<String,Utterance> postHM =new HashMap<String, Utterance>();
		double i =0;
		for (BPost post : items) {
			if(post== null || post.getAuthor()==null) continue;
			String postAuthorId = getAuthorName(post.getAuthor());
			if(post.getAuthor().getUrl()!=null)
				usersURL.add(post.getAuthor().getUrl());
			result.add(postAuthorId);
			
			Utterance parent = new Utterance(++i, 0 , postAuthorId, null, post.getPublished(), this.getBlogId());
			System.out.println("Process post no "+i + "out of "+items.size());
			//parent.setPostId(post.getId());
			parent.setText(Utils.escapeText(post.getContent()));
			parent.setPostAuthorId(postAuthorId);
			utterances.add(parent);
			addParticipationLog(parent);
			parent.setUserId(postAuthorId);
			postHM.put(post.getId(), parent);
		}
		for (BComment comment : comments) {
			if(comment== null || comment.getAuthor()==null) continue;
			String commAuthorId = getAuthorName(comment.getAuthor());
			if(comment.getAuthor().getUrl()!=null)
				usersURL.add(comment.getAuthor().getUrl());
			result.add(commAuthorId);
			Utterance parent = null;
			if(comment.getPost()== null || comment.getPost().getId()==null)
				continue;
			parent  = postHM.get(comment.getPost().getId());
			if(parent == null || parent.getId() == 0d) continue;
			Utterance child = new Utterance(++i, parent.getId() , commAuthorId, parent.getPostAuthorId(), comment.getDate(), this.getBlogId());
			System.out.println("Process comment no "+i + "out of "+comments.size());
			child.setText(Utils.escapeText(comment.getContent()));
			utterances.add(child);
			addParticipationLog(child);
		}
		
		return result;
	}
	
	public String getAuthorName(BAuthor a){
		String result = a.getDisplayName().toLowerCase().replaceAll(" ", "_");
		if(a.getEmail() != null && "".compareTo(a.getEmail())!=0 && "false".compareTo(a.getEmail())!=0)
			result+=a.getEmail();
		if(a.getID() != null && "".compareTo(a.getID())!=0 && "0".compareTo(a.getID())!=0)
			result+=a.getID();
		if(a.getId() != null && "".compareTo(a.getId())!=0 && "0".compareTo(a.getId())!=0)
			result+="_"+a.getId();
		return Utils.escapeText(result);
		
	}
	
	public void exportPolyCafe() throws IOException {
		
		StringBuffer userURL = new StringBuffer();
		FileOutputStream fop = null;
		File file;
        String filename = "polycafe_p"+users.size()+"_u"+utterances.size()+"_"+this.getBlogId().replaceAll(" ", "-");
        String extension = ".xml";
        file = new File("C:\\Users\\Dan\\workspace\\forumTransformID\\out\\"+filename+extension);
		fop = new FileOutputStream(file);
		// if file doesn't exists, then create it
		if (!file.exists()) {
			file.createNewFile();
		}

        String content    = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        content += "<Dialog team=\""+getBlogId()+"\">\n";
        content += "<Participants>\n";
        for (Iterator<String> it = users.iterator(); it.hasNext();) {
            String u = (String) it.next();
            content += "\t<Person nickname=\""+u+"\" />\n";
            //userURL.append(u.)
        }
        content +=    "</Participants>\n";
        content +=    "<Topics>\n";
        for (BPost post : items) {
        	content +=    "\t<Topic>";
            content +=    Utils.escapeText(post.getTitle());
            content +=    "</Topic>\n";
		}
        content +=    "</Topics>\n";
        content +=    "<Body>\n";
        byte[] contentInBytes = content.getBytes();
        fop.write(contentInBytes);
		fop.flush();
       long i=0;
       StringBuffer sb = new StringBuffer();
        for (Iterator<Utterance> it = utterances.iterator(); it.hasNext();) {
            Utterance utt = (Utterance) it.next();
            //if( !(u.getUserId() == null || u.getRefUserId()== null))
                //content += u.getUserId()+" "+u.getRefUserId()+"\n";
            System.out.println("Exporting utt: "+ (++i) + " out of"+utterances.size());
            sb.delete(0, sb.length());
            sb.append("\t<Turn nickname=\""+utt.getUserId()+"\" >\n");
            sb.append( "\t\t<Utterance genid=\""+utt.getId()+"\" ref=\""+utt.getRefId()+"\" time=\""+utt.getUtteranceTime()+"\">");
            sb.append( Utils.escapeText(utt.getText()));
            sb.append( "</Utterance>\n");
            sb.append( "\t</Turn>\n");
            contentInBytes = sb.toString().getBytes();
            fop.write(contentInBytes);
    		fop.flush();
        }

        sb.delete(0, sb.length());
        sb.append( "</Body>\n");
        sb.append( "</Dialog>\n");
        contentInBytes = sb.toString().getBytes();
        fop.write(contentInBytes);
		fop.flush();

		fop.close();
       
    }
	
	public TreeSet<String> getUsers() {
		return users;
	}
	public void setUsers(TreeSet<String> users) {
		this.users = users;
	}
	public List<Utterance> getUtterances() {
		return utterances;
	}
	public void setUtterances(List<Utterance> utterances) {
		this.utterances = utterances;
	}
	
	public void addParticipationLog(Utterance u){
		
		//check if it is existing user
		if( plList.containsKey(u.getUserId()) ){
			ParticipationLog log = plList.get(u.getUserId());
			log.addLog(u, true);
		}
		else{
			plList.put(u.getUserId(), new ParticipationLog(u,true));
		}
		
		//check if the ref user exist
		if( plList.containsKey(u.getRefUserId()) ){
			ParticipationLog log = plList.get(u.getRefUserId());
			log.addLog(u, false);
		}
		else{
			plList.put(u.getRefUserId(), new ParticipationLog(u,false));
		}
		
	}
	
	public String exportCSV(){
		StringBuffer result = new StringBuffer();
		result.append("User,No_Sent_Messages,No_Receive_Messages,No_Sent_Chars,No_Receive_Chars, No_Topics, No_Users_Receive, No_Users_Sent\n");
		for (Iterator<ParticipationLog> it = this.plList.values().iterator(); it.hasNext();) {
			ParticipationLog log = (ParticipationLog) it.next();
			result.append(log.exportCSV());
		}
		return result.toString();
	}

	public String exportUsersCSV(){
		StringBuffer result = new StringBuffer();
		result.append("Username - URL\n");
		for (Iterator<String> it = this.usersURL.iterator(); it.hasNext();) {
			String log = (String) it.next();
			result.append(log+"\n");
		}
		return result.toString();
	}

	
	public HashMap<String, ParticipationLog> getPlList() {
		return plList;
	}
	public void setPlList(HashMap<String, ParticipationLog> plList) {
		this.plList = plList;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public BPosts getPosts() {
		return posts;
	}
	public void setPosts(BPosts posts) {
		this.posts = posts;
	}
	public String getNextPageToken() {
		return nextPageToken;
	}
	public void setNextPageToken(String nextPageToken) {
		this.nextPageToken = nextPageToken;
	}
	public String getPrevPageToken() {
		return prevPageToken;
	}
	public void setPrevPageToken(String prevPageToken) {
		this.prevPageToken = prevPageToken;
	}
	public TreeSet<String> getUsersURL() {
		return usersURL;
	}
	public void setUsersURL(TreeSet<String> usersURL) {
		this.usersURL = usersURL;
	}
	
}
